package com.lungle.warmdiary.app.view.testcampaign.fragment.rate;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseListFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.base.ListBaseAdapter;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.CampaignMessageEvent;
import com.lungle.warmdiary.app.model.response.AppSummary;
import com.lungle.warmdiary.app.model.response.CampaignComment;
import com.lungle.warmdiary.app.model.response.CampaignCommentList;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.testcampaign.adapter.CampaignDetailListAdapter;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public abstract class CampaignRateFragment extends BaseListFragment<CampaignListItem1> {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isActive = false;
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initData();

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        isActive = false;
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //    int productid;
    String campaignid;

    private String icon;
    private String title;
    private int rate;

    private List<CampaignListItem1> list = new ArrayList<CampaignListItem1>();
//    AppSummary appSummary = new AppSummary();

    @Override
    public void initData() {
        Intent intent = getActivity().getIntent();
//        productid = intent.getIntExtra("productid", 0);
        campaignid = intent.getStringExtra("campaignid");
        icon = intent.getStringExtra("icon");
        title = intent.getStringExtra("title");
        rate = intent.getIntExtra("rate", 0);

//        appSummary.setIcon(icon);
//        appSummary.setRate(rate);
//        appSummary.setTitle(title);

    }

    @Override
    public void initView(View view) {
        super.initView(view);

    }

    @Override
    protected void sendRequestData() {
        super.sendRequestData();
        if (TextUtils.isEmpty(produceId)) return;
        if (list != null) {
            if (mCurrentPage == 0) {
                list.clear();
                ApiFactory.getUserApi().getSummary(produceId)
                        .compose(this.<Result<AppSummary>>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .map(new Func1<Result<AppSummary>, Result<List<CampaignListItem1>>>() {

                            @Override
                            public Result<List<CampaignListItem1>> call(Result<AppSummary> campaignCommentListResult) {
                                list.add(new CampaignListItem1(campaignCommentListResult.getData()));
                                Result<List<CampaignListItem1>> r = new Result<List<CampaignListItem1>>();
                                r.setData(list);

                                return r;
                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseSubscriber<Result<List<CampaignListItem1>>>() {
                            @Override
                            public void onCompleted() {
                                super.onCompleted();
                                getlist();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                            }

                            @Override
                            public void onNext(Result<List<CampaignListItem1>> listResult) {
                                super.onNext(listResult);
                            }
                        });


            } else {
                list.clear();
                getlist();
            }
        }


    }


    private void getlist() {
        ApiFactory.getUserApi().getCampaignDetailList(produceId, getRate(), mCurrentPage * getPageSize(), getPageSize())
                .compose(this.<Result<CampaignCommentList>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .map(new Func1<Result<CampaignCommentList>, Result<List<CampaignListItem1>>>() {

                    @Override
                    public Result<List<CampaignListItem1>> call(Result<CampaignCommentList> campaignCommentListResult) {
                        for (CampaignComment campaignComment : campaignCommentListResult.getData().getData()) {
                            campaignComment.setShareLink(shareLink);
                            campaignComment.setShareLinkTitle(shareLinkTitle);
                            campaignComment.setCampaignStatus(campaignStatus);
                            list.add(new CampaignListItem1(campaignComment));
                        }

                        Result<List<CampaignListItem1>> r = new Result<List<CampaignListItem1>>();
                        r.setData(list);

                        return r;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mSubscriber);
    }

    @Override
    protected ListBaseAdapter getListAdapter() {
        CampaignDetailListAdapter adapter = new CampaignDetailListAdapter(getActivity());
        return adapter;
    }

    @Override
    protected CampaignCommentList parseList(InputStream is) throws Exception {
        return CampaignCommentList.parse(is);
    }


    @Override
    protected CampaignCommentList readList(Serializable seri) {
        return (CampaignCommentList) seri;
    }


    @Override
    protected boolean requestDataIfViewCreated() {
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        CampaignListItem1 item = mAdapter.getItem(position);
        if (item != null) {
            if (item.getTYPE() == 0)
                UIHelper.showCampaignCommentDetail(getActivity(), item.getCampaignComment());
        }
    }

    abstract int getRate();


    String produceId;
    String shareLink;
    String shareLinkTitle;
    int campaignStatus;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void campaigMessage(CampaignMessageEvent event) {
        produceId = event.getProduceId();
        campaignStatus = event.getStatus();
        shareLinkTitle = event.getShareLinkTitle();
        LogUtils.printLogE("CampaignMessageEvent " + produceId);
        shareLink = event.getShareLinK();
        sendRequestData();
    }
}
